package com.yonyou.brigade.third_parties.meiya.controller;

import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.model.IChannelConfig;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.meiya.model.MeiyaConfig;
import com.yonyou.brigade.third_parties.meiya.model.MeiyaUser;
import com.yonyou.brigade.third_parties.meiya.service.IMeiyaUserService;
import com.yonyou.brigade.third_parties.meiya.util.MeiyaUserConvertUtil;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * 美亚商旅用户 controller
 *
 * @author kangfw5
 * @since 2019-06-12
 */
@RestController
@RequestMapping("/meiya")
public class MeiyaUserController {
    @Autowired
    private IMeiyaUserService meiyaUserService;
    @Autowired
    private IBriChannelService briChannelService;
    @Autowired
    private IUserCenterService userCenterService;

    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public void login(String tenant, String org, String phone, String pageType, HttpServletResponse response) throws IOException {
        String loginUrl = meiyaUserService.getLoginUrl(tenant, org, phone, pageType, "H5", null);
        response.sendRedirect(loginUrl);
    }

    @RequestMapping(path = "/syncUser", method = RequestMethod.POST)
    public void syncUser(String tenant, String org, String phone){
        BriChannel briChannel = briChannelService.getEnableInfoByTenantOrg(tenant, org, ChannelEnum.MEIYA.getName());
        if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
            IChannelConfig channelConfig = briChannelService.getChannelConfig(tenant, ChannelEnum.MEIYA.getName(), org, new MeiyaConfig());
            UcUserDto ucUserDto = userCenterService.getCompleteUcUserDtoByPhone(phone, tenant);
            MeiyaConfig meiyaConfig = (MeiyaConfig) channelConfig;
            MeiyaUser meiyaUser = MeiyaUserConvertUtil.ucUser2Meiya(tenant, meiyaConfig.getCompanyId(), ucUserDto);
            meiyaUserService.syncUsers(channelConfig, Collections.singletonList(meiyaUser), briChannel);
            meiyaUserService.insert(meiyaUser);
        }
    }
}
